#define _GNU_SOURCE
#include "app_serial2.h"
#include "log/log.h"
#include <stdlib.h>



SerialDevice2 *app_serial2_init(char *filename){
    Device *device = app_device_init(filename);
    if (!device)
    {
        log_error("app_device_init error");
        goto DEVICE_INIT_FAIL;
    }
    SerialDevice2 *serial = realloc(device, sizeof(SerialDevice2));
    if (!serial)
    {
        log_error("realloc error");
        goto SERIAL_INIT_FAIL;
    }
    if(app_serial_setBraudRate2(serial,BR_115200)!=0){
        log_error("app_serial_setBraudRate2 error");
        goto SERIAL_INIT_FAIL;
    }
    if (app_serial_setParity2(serial,Parity_None)!=0)
    {
        log_error("app_serial_setParity2 error");
        goto SERIAL_INIT_FAIL;
    }

    if (app_serial_setStopBits2(serial,StopBits_1)!=0)
    {
        log_error("app_serial_setStopBits2 error");
        goto SERIAL_INIT_FAIL;
    }

    tcflush(serial->supre.fd,TCIOFLUSH);

    return serial;   
DEVICE_INIT_FAIL:
    return NULL;
SERIAL_INIT_FAIL:
    app_device_close(device);
}

/**
 * 设置波特率
 */
int app_serial_setBraudRate2(SerialDevice2 *serial, BraudRate braud_rate){
    serial->brand_rate = braud_rate;
    struct  termios termios;

    if(tcgetattr(serial->supre.fd, &termios) != 0){
        log_error("tcgetattr error");
        return -1;
    }
    cfsetspeed(&termios, braud_rate);
    if(tcsetattr(serial->supre.fd,TCSANOW, &termios) != 0){
        log_error("tcsetattr error");
        return -1;

    }
    return 0;
}
/**
 * 设置校验位
 */
int app_serial_setParity2(SerialDevice2 *serial, Parity parity){
    serial->parity = parity;
    struct  termios termios;

    if(tcgetattr(serial->supre.fd, &termios) != 0){
        log_error("tcgetattr error");
        return -1;
    }
    termios.c_cflag &= ~(PARENB | PARODD);//清除校验位
    termios.c_cflag |= parity; // 设置校验位

    if(tcsetattr(serial->supre.fd,TCSANOW, &termios) != 0){
        log_error("tcsetattr error");
        return -1;
    }
    return 0;
}

/**
 * 设置停止位
 */
int app_serial_setStopBits2(SerialDevice2 *serial, StopBits stop_bits){
    serial->stop_bits = stop_bits;
    struct  termios termios;
    if(tcgetattr(serial->supre.fd,&termios)!=0){
        log_error("tcgetattr error");
        return -1;
    }
    termios.c_cflag &= ~CSTOPB; // 清除停止位
    termios.c_cflag |= stop_bits; // 设置停止位
    if(tcsetattr(serial->supre.fd,TCSANOW, &termios) != 0){
        log_error("tcsetattr error");
        return -1;
    }
    return 0;
}

/**
 * 设置连接类型
 */
int app_serial_setConnectionType2(SerialDevice2 *serial, ConnectionType conn_type);